﻿function VideoChatCtrl($rootScope,$scope,$http,$timeout){
		var apiKey = ""; // Replace with your API key. See https://dashboard.tokbox.com/projects
		var sessionId = ""; // Replace with your own session ID. See https://dashboard.tokbox.com/projects
		var token = ''; // Replace with a generated token. See https://dashboard.tokbox.com/projects
		
		var session;
		var publisher;
		var subscribers = {};
		var VIDEO_WIDTH = 160;
		var VIDEO_HEIGHT = 120;
		var WAIT_FOR_CALL = 30000;
		
		var CALLER_VIDEO_HEIGHT = Math.round($(window).height()/2);
		if (CALLER_VIDEO_HEIGHT>400) {CALLER_VIDEO_HEIGHT=400;}
		var CALLER_VIDEO_WIDTH = Math.round(CALLER_VIDEO_HEIGHT*(4/3));
		
		var CALLER_VIDEO_HEIGHT = Math.round($(window).height());

		var CALLER_VIDEO_WIDTH = Math.round($(window).width()*0.6);
		
	
		
		$scope.CALL_STATUS_WAINTING_FOR_RECIPIENT="CALL_STATUS_WAINTING_FOR_RECIPIENT";
		$scope.CALL_STATUS_INCOMING_CALL="CALL_STATUS_INCOMING_CALL";
		$scope.CALL_STATUS_IN_CHAT="CALL_STATUS_IN_CHAT";
		$scope.CALL_STATUS_DISCONNECTED="CALL_STATUS_DISCONNECTED";
		$scope.CALL_STATUS_LOADING="CALL_STATUS_LOADING";
		$scope.CALL_STATUS_NO_ANSWER="CALL_STATUS_NO_ANSWER";
		
		
		
		var oldwidth,oldheight,oldtop,oldleft;
		$scope.changeCallStatus = function(newStatus){
			var oldStatus=$scope.callStatus;
			$scope.callStatus=newStatus;
			
			if (newStatus!=$scope.CALL_STATUS_INCOMING_CALL && newStatus!=$scope.CALL_STATUS_WAINTING_FOR_RECIPIENT) {
				$rootScope.$broadcast('videoChatStopSounds');
			}
			
			
			if (newStatus==$scope.CALL_STATUS_IN_CHAT){
				
				oldwidth=$('#chatPopUp').css("width");
				oldheight=$('#chatPopUp').css("height");
				oldtop=$('#chatPopUp').css("top");
				oldleft=$('#chatPopUp').css("left");
				
				$('#chatPopUp').animate({
					width: '100%',
					height: '100%',
					top: '0px',
					left: '0px'
				  },1000,
					  
					  function(){
						   //$( ".videoChatBox" ).css("width",Math.round($(window).width()*0.6)+"px");
						   $( ".videoChatBox" ).css("width","58%");
						  $( ".videoChatModal" ).addClass("videoChatModalFull");
						  //$( ".chatArea" ).css("width",($(window).width()-Math.round($(window).width()*0.6))+"px");
						  $( ".chatArea" ).css("width","40%");
						  $( ".chatArea" ).addClass("chatAreaFull");
						  $( ".formArea" ).css("width","40%");
						  $( ".formArea" ).addClass("formAreaWrapFull");
						  $("#home_link").trigger("click");
						  
					  }
				  );
				
				  
				 
			} else if (oldStatus==$scope.CALL_STATUS_IN_CHAT){
					$timeout(function(){
					$('#chatPopUp').animate({
					width: oldwidth,
					height: oldheight,
					top: oldtop,
					left: oldleft
				  });
				  $( ".videoChatBox" ).css("width","");
				  $( ".videoChatModal" ).removeClass("videoChatModalFull");
				  $( ".chatArea" ).css("width","");
				  $( ".chatArea" ).removeClass("chatAreaFull");
				  $( ".formArea" ).css("width","");
				  $( ".formArea" ).removeClass("formAreaWrapFull");
				  },10);
			} else if(oldStatus==$scope.CALL_STATUS_DISCONNECTED){
			
			}
		}
		
		$scope.callStatus=$scope.CALL_STATUS_WAINTING_FOR_RECIPIENT;
		$scope.callerFlg=false;
		$scope.inChatWithName="";
		
		var noAnswerTimer = null;
		$scope.$on('initVideoChat', function(event,argsObj) {
			$timeout.cancel(noAnswerTimer);
			$scope.callerFlg=argsObj.callerFlg;
			if($scope.callerFlg){
				$scope.changeCallStatus($scope.CALL_STATUS_WAINTING_FOR_RECIPIENT);
				$scope.inChatWithName=argsObj.recipientName;
				noAnswerTimer=$timeout(function(){checkNoAnswer()},WAIT_FOR_CALL);
			} else {
				$scope.changeCallStatus($scope.CALL_STATUS_INCOMING_CALL);
				$scope.inChatWithName=argsObj.callerName;
			}
			$scope.init(argsObj.sessionId,argsObj.token);
			
			$timeout(function(){$rootScope.$broadcast('videoChatPopupOpen')},1);
		});
		
				
		$scope.$on('connectVideoChat', function(event,argsObj) {
			console.log('connectVideoChat');
			$scope.answerCall(true);
		});
		
		$scope.$on('disconnectVideoChat', function(event,argsObj) {
			console.log('disconnectVideoChat');
			$scope.disconnect(true);
		});
		
		
			

		var isConnectedFlg=false;
		var forcePublishingFlg=false; //i use this in case we answerd a call before connection to session was finished
		
		
		$scope.init=function(tmp_sessionId,tmp_token){
				isConnectedFlg=false;
				forcePublishingFlg=false;
				apiKey="22129482"
				sessionId=tmp_sessionId;
				token=tmp_token;
				
				session = null;
				publisher= null;
				subscribers = {};
		
		
				TB.addEventListener("exception", exceptionHandler);
				
				
	
				if (TB.checkSystemRequirements() != TB.HAS_REQUIREMENTS) {
					console.log("ERROR NO REQUIREMENTS");
				} else {
					TB.warn=function(){};
					TB.log=function(){};
					TB.debug=function(){};
					TB.error=function(){};
					TB.info=function(){};
					session = TB.initSession(sessionId);	
				
					session.addEventListener('sessionConnected', sessionConnectedHandler);
					session.addEventListener('sessionDisconnected', sessionDisconnectedHandler);
					session.addEventListener('connectionCreated', connectionCreatedHandler);
					session.addEventListener('connectionDestroyed', connectionDestroyedHandler);
					session.addEventListener('streamCreated', streamCreatedHandler);
					session.addEventListener('streamDestroyed', streamDestroyedHandler);
					$scope.connect();
				}

		}
	
	
		$scope.connect = function() {
			
			session.connect(apiKey, token);
		}
		
	

		$scope.disconnect = function(dontBroadCastFlg) {
			if (isConnectedFlg) {
				isConnectedFlg=false;
				session.disconnect();
			}
			closeChatPopup();
			if (!dontBroadCastFlg) {
				$rootScope.$broadcast('videoChatChangeStatus',false);
			}
		}
		
		function closeChatPopup(){
			if ($scope.callStatus!=$scope.CALL_STATUS_NO_ANSWER){
				$scope.changeCallStatus($scope.CALL_STATUS_DISCONNECTED);
			} 
			$timeout(function(){
			$rootScope.$broadcast('videoChatPopupClose')
			$scope.changeCallStatus("");
			},2000);
			
		}

		// Called when user wants to start publishing to the session
		$scope.startPublishing= function() {
			$scope.changeCallStatus($scope.CALL_STATUS_IN_CHAT);
			publisher=null;
			if (!publisher) {
			
				var parentDiv = $("#myCamera");
				$("#myCamera").html('');
				
				var publisherDiv = document.createElement('div'); // Create a div for the publisher to replace
				publisherDiv.setAttribute('id', 'opentok_publisher');
				parentDiv.append(publisherDiv);
				var publisherProps = {width: VIDEO_WIDTH, height: VIDEO_HEIGHT};
			
				publisher = TB.initPublisher(apiKey, publisherDiv.id, publisherProps);  // Pass the replacement div id and properties
				publisher.addEventListener("accessAllowed",
                           accessAllowedHandler);
			
				
				session.publish(publisher);
			}
		}
		
		function accessAllowedHandler(event) {
			$timeout(function(){$("#myCamera").addClass("applyEffect")},2000);
		}
		function checkNoAnswer(){
			console.log('checkNoAnswer');
			if ($scope.callStatus==$scope.CALL_STATUS_WAINTING_FOR_RECIPIENT) {
				console.log('no answer');
				$scope.changeCallStatus($scope.CALL_STATUS_NO_ANSWER);
				$scope.disconnect(false);
				
			}
		}

		$scope.stopPublishing =  function() {
			if (publisher) {
				session.unpublish(publisher);
			}
			publisher = null;

		}
		$scope.answerCall = function(dontBroadCastFlg){
			$scope.changeCallStatus($scope.CALL_STATUS_LOADING);
			if (!dontBroadCastFlg) {
				
				$rootScope.$broadcast('videoChatChangeStatus',true)
			}
			
			if (isConnectedFlg) {
			$scope.startPublishing();
			} else {
				forcePublishingFlg=true;
				console.log("notConnectedYet")
			}
		}
		

		//--------------------------------------
		//  OPENTOK EVENT HANDLERS
		//--------------------------------------

		var sessionConnectedHandler =  function(event) {
			// Subscribe to all streams currently in the Session
				console.log('event.streams');
				console.log(event.streams);
				console.log('subscribers');
				console.log(subscribers);
				$("#subscribers").html('');
			for (var i = 0; i < event.streams.length; i++) {
				addStream(event.streams[i]);
			}
			isConnectedFlg=true;
			console.log("sessionConnectedHandler");
					
			if (forcePublishingFlg) {
				$scope.startPublishing();
			}
		}

		function streamCreatedHandler(event) {
			// Subscribe to the newly created streams
			for (var i = 0; i < event.streams.length; i++) {
				addStream(event.streams[i]);
			}
	
			fixPopupLocation();
		}

		function streamDestroyedHandler(event) {
			// This signals that a stream was destroyed. Any Subscribers will automatically be removed.
			// This default behaviour can be prevented using event.preventDefault()
			
			$timeout(function(){$scope.disconnect(true)},2000);
		}

		function sessionDisconnectedHandler(event) {
			// This signals that the user was disconnected from the Session. Any subscribers and publishers
			// will automatically be removed. This default behaviour can be prevented using event.preventDefault()
			publisher = null;
			isConnectedFlg = false;
			subscribers={};
			//closeChatPopup();
		}

		function connectionDestroyedHandler(event) {
			// This signals that connections were destroyed
		}

		function connectionCreatedHandler(event) {
			// This signals new connections have been created.
		}

		/*
		If you un-comment the call to TB.setLogLevel(), above, OpenTok automatically displays exception event messages.
		*/
		function exceptionHandler(event) {
		}

		//--------------------------------------
		//  HELPER METHODS
		//--------------------------------------

		function addStream(stream) {
			// Check if this is the stream that I am publishing, and if so do not publish.
			if (stream.connection.connectionId == session.connection.connectionId) {
				return;
			}
			var subscriberDiv = document.createElement('div'); // Create a div for the subscriber to replace
			subscriberDiv.setAttribute('id', stream.streamId); // Give the replacement div the id of the stream as its id.
			document.getElementById("subscribers").appendChild(subscriberDiv);
			var subscriberProps = {width: CALLER_VIDEO_WIDTH, height: CALLER_VIDEO_HEIGHT};
			subscribers[stream.streamId] = session.subscribe(stream, subscriberDiv.id, subscriberProps);
			fixPopupLocation();
		}
		
		function fixPopupLocation(){
			$timeout(function(){$(window).trigger('resize')},100);
		}

		function show(id) {
			
		}

		function hide(id) {
			
		}
		
		
		
	
		}
		
		